package com.eqgis.eqtool.tmp;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class EasyIoHelper {
    private OnUpdateListener onUpdateListener;
    public interface OnUpdateListener{
        void onUpdate(String lineStr);
    }

    public void setOnUpdateListener(OnUpdateListener onUpdateListener) {
        this.onUpdateListener = onUpdateListener;
    }

    /**
     * ��ȡ�ַ���
     * @param filePath
     * @return
     */
    public String readString(String filePath){
        StringBuffer stringBuffer = new StringBuffer();
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            InputStreamReader is = null;
            is = new InputStreamReader(fileInputStream);
            BufferedReader reader = new BufferedReader(is);
            String line;

            if (onUpdateListener != null){
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line);
                    onUpdateListener.onUpdate(line);
                }
            }else {
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line);
                }
            }
            is.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    /**
     * д���ַ�����ָ���ļ�
     * @return
     */
    public boolean writeString(String filePath,String sourceStr){
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            OutputStreamWriter os = new OutputStreamWriter(fileOutputStream);
            os.write(sourceStr);

            os.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
